/*
 * Galaxium Messenger
 *
 * Copyright (C) 2007 Paul Burton <paulburton89@gmail.com>
 * Copyright (C) 2007 Philippe Durand <draekz@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;

using Galaxium.Core;
using Galaxium.Protocol;

using Anculus.Core;

namespace Galaxium.Gui
{
	public class CustomEmoticonInfo
	{
		internal IConfigurationSection _config;
		
		public CustomEmoticonInfo(IConfigurationSection config)
		{
			_config = config;
			_allowedAccount = _config.Parent.Parent.Name;
			_allowedDest = _config.Parent.Name;
			
			LoadEmoticon();
		}
		
		IEmoticon _emoticon;
		public IEmoticon Emoticon
		{
			get { return _emoticon; }
		}
		
		string _allowedAccount;
		public string AllowedAccount
		{
			get { return _allowedAccount; }
			set
			{
				if (_allowedAccount == value)
					return;
				
				_allowedAccount = value;
				RecreateConfig();
			}
		}
		
		string _allowedDest;
		public string AllowedDestination
		{
			get { return _allowedDest; }
			set
			{
				if (_allowedDest == value)
					return;
				
				_allowedDest = value;
				RecreateConfig();
			}
		}
		
		void LoadEmoticon()
		{
			string[] equivalents = _config.GetString("Equivalents").Split(new char[] { ' ' });
			string filename = _config.GetString("Filename");
					
			_emoticon = new BaseEmoticon(_config.Name, equivalents, filename, new byte[0]);
		}
		
		void RecreateConfig()
		{
			IConfigurationSection newconfig = EmoticonUtility._config[_allowedAccount][_allowedDest][_emoticon.Name];
			
			newconfig.SetString("Filename", _config.GetString("Filename"));
			newconfig.SetString("Equivalents", _config.GetString("Equivalents"));
			
			_config.Parent.RemoveSection(_config.Name);
			
			_config = newconfig;
		}
		
		public bool Allow(IAccount account, IContact dest)
		{
			bool allowAccount = (account == null) || (_allowedAccount == "*") || (_allowedAccount == account.UniqueIdentifier);
			bool allowDest = (dest == null) || (_allowedDest == "*") || (_allowedDest == dest.UniqueIdentifier);
			
			return allowAccount && allowDest;
		}
		
		public void SetEquivalents(string equivalents)
		{
			_config.SetString("Equivalents", equivalents);
			LoadEmoticon();
		}
	}
}
